package com.example.demo1.service.servicelmpl;
import com.example.demo1.service.DataDetectionService;
import com.example.demo1.utils.DetectionResult;
import com.example.demo1.entity.Timepoint;
import com.example.demo1.service.Yolov8Service;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

@Service
public class DataDetectionServices implements DataDetectionService {
    //1.接收数据
    @Resource
    private Yolov8Service yolov8Service;
    List<DetectionResult> results= new ArrayList<>();
    float nums=0;
    int i=0;
    public  List<DetectionResult>  DataDetection(List<Timepoint> timePoints) throws Exception {
    for(Timepoint timepoint: timePoints){
        for(Timepoint.Category category : timepoint.getCategories()){
            String folderPath = category.getFileUrl();
            if (folderPath!=null && !folderPath.isEmpty()){
                List<String> imageUrls =getImageurl(folderPath); //2.获得数据每个路径
                for(String imageUrl: imageUrls){  //3.调用yolov9模型（service）, 进行计算
                          nums+=yolov8Service.Yolov8(imageUrl);
                          i++;

                }
                    float infectdata = (float) nums/ i ;
                    DetectionResult result =new DetectionResult();
                    result.setTime_point(timepoint.getTime());
                    result.setGroup_name(category.getGroup_name());
                    result.setInfectdata(infectdata);
                    results.add(result);
        }
      }
    }
                     return  results;
}


  public List<String> getImageurl(String path) {
      List<String> imageUrls  = new ArrayList<>();
      File folder = new File(path);
      if (folder.exists() && folder.isDirectory()) {
          File[] files = folder.listFiles(new FilenameFilter() {
              @Override
              public boolean accept(File dir, String name) {
                  String lowerCaseName = name.toLowerCase();
                  return lowerCaseName.endsWith(".jpg") ||
                          lowerCaseName.endsWith(".jpeg") ||
                          lowerCaseName.endsWith(".png") ||
                          lowerCaseName.endsWith(".gif");
              }
          });
          if (files != null) {
              for (File file : files) {
                  if (file.isFile()) {
                      imageUrls.add(file.getAbsolutePath());
                  }
              }
          }
      } else {
          System.out.println("The provided path is not a valid directory: " + path);
      }
      return imageUrls;
  }

}